const path = require('path')
const fs = require('fs')
var express = require('express');
var router = express.Router();
const multer = require('multer')
const logger = require('../../_unit/logs')

const upload = multer({
  dest: path.resolve(__dirname, '../public/uploads')
})

/* GET home page. */
router.get('/', function (req, res, next) {
  // res.render('index', { title: 'Express' });
  res.render('a/indexHome', { name: 'Jackie Chan' });
});


router.get('/upload', function (req, res, next) {
  res.render('upload', { user: "wq", fileName: "ssyy" })
});

router.post('/upload', upload.single('uploaded_file'), function (req, res, next) {
  let newFileName = `${req.file.filename}-${req.file.originalname}`;
  let newFilePath = path.resolve(__dirname, '../public/uploads/', newFileName)
  // 重命名图片
  fs.renameSync(req.file.path, newFilePath)

  res.send(`<img src='/uploads/${newFileName}'/>`)
});

router.post('/delFile', function (req, res, next) {
  let uploads = path.resolve(__dirname, '../public/uploads/')
  fs.readdir(uploads, (err, files) => {
    if (err) new Error(err)
    files.forEach(item => {
      fs.rmSync(path.resolve(uploads, `./${item}`))
    });
    res.send('1212')
    // next()
  })
});

module.exports = router;
